package org.example.bootquartz.service.impl;

import org.example.bootquartz.common.R;
import org.example.bootquartz.service.QuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 季舟
 * @Date 2025-02-07 15:18
 */
@Service
public class QuartzServiceImpl implements QuartzService {
    @Autowired
    private Scheduler scheduler;

    public R addCronjob(String jobName, String jobGroup, String jobClassName, String cron, String triggerName, String triggerGroup){
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
            if (scheduler.checkExists(jobKey)){
                return R.error("任务已存在");
            }
            JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(jobClassName))
                    .withIdentity(jobName, jobGroup)
                    .withDescription("任务描述")
                    .build();
            CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(triggerName,triggerGroup))
                    .withSchedule(cronSchedule)
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("任务创建失败："+e.getMessage());
        }
        return R.success("任务创建成功");
    }
}
